<script setup lang="ts">
  import { PropType, ref } from "vue";
  import { ElForm, ElFormItem, FormInstance } from "element-plus";
  import StockSelect from "./StockSelect.vue";
  const
    props = defineProps({
      modelValue: { type: Object as PropType<gt.sql.order>, default: format.def.order, },
      curd: { type: Number as PropType<gt.curd>, default: 2 }
    }),
    stockSelect = ref<InstanceType<typeof StockSelect>>(),
    rules = ref({
      name: { required: true, message: "请填写标题", trigger: "blur", min: 1 },
      type: { required: true, message: "请选择商品类型", trigger: "blur", min: 1 },
      oid: { required: true, message: "请选择配送商户", trigger: "blur", min: 1 },
    }),
    gs = ref<Tree<gt.sql.group>>([]),
    opt = ref({
      expandTrigger: "hover",
      checkStrictly: true,
      emitPath: false,
      value: "id",
      label: "name"
    }),
    entity = ref<FormInstance>();

  function changePid() {
    if (!props.modelValue.oid) {
      props.modelValue.oid = "";
    }
  }
  async function init() {
    if (!gs.value.length) {
      const t = (await gd.groupTree).find(e => e.id === "1");
      if (t) {
        gs.value = t.children as any;
      }
    }
  }
  init();
  function addOut() {
    stockSelect.value?.open(1).then(async (p) => {
      if (p) {
        const s = props.modelValue.content.out.find(e => e.stock == p.id);
        if (s) {
          s.sum = (s.sum || 0) + 1;
        } else {
          props.modelValue.content.out.push(await format.stockLog({
            stock: p.id,
            max: p.sum
          }));
        }
        setOut();
      }
    });
  }
  function sumChange(p: gt.sql.stockLog) {
    const i = props.modelValue.content.out.indexOf(p);
    if (i >= 0) {
      props.modelValue.content.in[i].sum = p.sum;
    }
  }
  async function setOut() {
    const group = await gd.group.getById(props.modelValue.oid);
    props.modelValue.content.in = props.modelValue.content.out.map((e, i) => {
      console.log(e);
      return {
        _stock: { _group: group, _goods: e._stock?._goods } as any,
        gid: group?.id,
        goods: e._stock?.goods,
        sum: e.sum,
        des: props.modelValue.content.in[i]?.des || ""
      };
    });
  }
  function delRow(p: gt.sql.stockLog) {
    props.modelValue.content.out.splice(props.modelValue.content.out.indexOf(p), 1);
    setOut();
  }

  defineExpose({
    validate() {
      return new Promise<boolean>(async (resolve) => {
        if (!props.curd) {
          const { content } = props.modelValue;
          for (let i = 0; i < content.out.length; i++) {
            if (!content.out[i].sum) {
              ElMessageBox.confirm(`出库详情第[${i + 1}]行未选择数量`, "错误", { type: "error", });
              return resolve(false);
            }
          }
        }

        if (entity.value) {
          entity.value.validate().then(resolve).catch(() => { resolve(false); });
        } else {
          resolve(false);
        }
      });
    },
    resetFields() { entity.value?.resetFields(); }
  });
</script>
<template>
  <ElForm class="order xw zb" ref="entity" :model="modelValue" :rules="rules" labelWidth="7em">
    <ElFormItem label="id" prop="id">
      <el-input v-model="modelValue.id" disabled placeholder="系统自动生成" />
    </ElFormItem>
    <ElFormItem label="创建时间" prop="createTime">
      <el-input :modelValue="modelValue.createTime ? modelValue._createTime : '系统自动生成'" disabled />
    </ElFormItem>
    <ElFormItem label="交付时间" prop="createTime">
      <el-input :modelValue="modelValue.payTime ? modelValue._payTime : '未交付'" disabled />
    </ElFormItem>
    <ElFormItem label="操作人" prop="_user.name">
      <el-input :modelValue="modelValue._user?.name" placeholder="系统自动生成" disabled />
    </ElFormItem>
    <ElFormItem label="目标商户" prop="oid">
      <el-cascader v-model="modelValue.oid" :options="gs" :props="opt" :disabled="curd == 2" clearable
        collapse-tags-tooltip placeholder="请选择 商户" @change="changePid" />
    </ElFormItem>
    <ElFormItem label="标题" prop="name">
      <el-input v-model="modelValue.name" placeholder="请输入名称" :disabled="curd == 2" />
    </ElFormItem>
    <ElFormItem label="备注" prop="des" class="wf">
      <el-input v-model="modelValue.des" placeholder="请输入备注" :disabled="curd == 2" />
    </ElFormItem>
    <ElFormItem class="wf" label="出库详情" prop="banner">
      <template #label>
        <div class="whf y je">
          <div class="el-form-item__label">出库详情</div>
          <el-button type="primary" class="mt1em" @click="addOut" :disabled="!!curd || !modelValue.oid">新增</el-button>
        </div>
      </template>
      <el-table stripe highlight-current-row :data="modelValue.content.out" class="wf ox" height="15em" type="expand"
        row-key="id">
        <el-table-column prop="_stock._group?.name" label="库存" width="100" show-overflow-tooltip />
        <el-table-column prop="_stock._goods?.name" label="商品名称" show-overflow-tooltip />
        <el-table-column prop="_stock._goods?.money" label="单价" show-overflow-tooltip />
        <el-table-column prop="sum" label="数量" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input-number class="wf" v-model="row.sum" :min="!!curd ? undefined : 0" :max="row._stock?.sum"
              :disabled="!!curd" @input="sumChange(row)" />
          </template>
        </el-table-column>
        <el-table-column prop="des" label="备注" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="wf x oh jc">
              <el-input class="wf" v-model="row.des" :disabled="!!curd" />
              <div v-if="curd < 2" class="ml04em sbss cr mac-ico-delete" @click="delRow(row)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="_createTime" label="创建时间" width="120" show-overflow-tooltip />
        <el-table-column prop="_user.name" label="创建人" width="100" show-overflow-tooltip />
      </el-table>
    </ElFormItem>
    <ElFormItem class="wf" label="入库详情" prop="banner">
      <template #label>
        <div class="whf y je">
          <div class="el-form-item__label">入库详情</div>
          <!-- <el-button type="primary" class="mt1em" @click="addIn" :disabled="!!curd">新增</el-button> -->
        </div>
      </template>
      <el-table stripe highlight-current-row :data="modelValue.content.in" class="wf" height="15em" type="expand"
        row-key="id">
        <el-table-column prop="_stock._group?.name" label="库存" width="100" show-overflow-tooltip />
        <el-table-column prop="_stock._goods?.name" label="商品名称" show-overflow-tooltip />
        <el-table-column prop="_stock._goods?.money" label="单价" show-overflow-tooltip />
        <el-table-column prop="sum" label="数量" width="160" show-overflow-tooltip />
        <el-table-column prop="des" label="备注" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input class="wf" v-model="row.des" :disabled="!!curd" />
          </template>
        </el-table-column>
        <el-table-column prop="_createTime" label="创建时间" width="120" show-overflow-tooltip />
        <el-table-column prop="_user.name" label="创建人" width="100" show-overflow-tooltip />
      </el-table>
    </ElFormItem>
    <StockSelect ref="stockSelect" />
  </ElForm>
</template>
<style lang="scss" scoped>
  .order {
    position: relative;
    >.el-form-item:not(.wf) {
      width: 49%;
    }
  }
</style>